#include<stdio.h>
#include<string.h>                                                              
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>

int a=0;
int count=0;

pthread_mutex_t mtx;
pthread_cond_t cond;

void* thread1(void* arg)
{
    for(int i=0;i<10;i++)
    {
        pthread_mutex_lock(&mtx);
        if(a!=0)
        {
            pthread_cond_wait(&cond,&mtx);
        }
        printf("a = %d\n",++a);
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mtx);
    }
}

void* thread2(void* arg)
{
   for(int i=0;i<10;i++)
    {
        pthread_mutex_lock(&mtx);
        if(a!=1)
        {
            pthread_cond_wait(&cond,&mtx);
        }
        printf("a = %d\n",--a);
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mtx);
    }
}

void* thread3(void* arg)
{
    for(int i=0;i<10;i++)
    {
        pthread_mutex_lock(&mtx);
        if(a==1)
        {
            printf("a = %d\n",--a);
            count++;
        }
        pthread_mutex_unlock(&mtx);
    }
}

int main(int argc, char* argv[])
{
    pthread_mutex_init(&mtx,NULL);

    pthread_t tid1,tid2,tid3;

    pthread_create(&tid1,NULL,thread1,NULL);
    pthread_create(&tid2,NULL,thread2,NULL);
    pthread_create(&tid3,NULL,thread3,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);

    printf("count = %d\n",count);

    pthread_mutex_destroy(&mtx);
    
    return 0;
}


